package com.bkfm.framework.sys.utils;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.yak.common.digest.Md5Utils;
import org.yak.core.exception.ServiceException;
import org.yak.core.utils.ConfigUtils;

import com.bkfm.framework.core.constants.BkfmConstants;
import com.bkfm.framework.sys.api.service.IBkfmCustomLoginService;
import com.bkfm.framework.sys.entity.BkfmMenu;
import com.bkfm.framework.sys.entity.BkfmUserOrgs;
import com.bkfm.framework.sys.entity.CurrentUser;

public class BkfmUserUtils {
	
	private static final Logger logger = Logger.getLogger(BkfmUserUtils.class);
	/**
	 * 获取登录用户
	 * @return
	 */
	public static CurrentUser getCurrentUser() {
		Subject sub = SecurityUtils.getSubject();
		return (CurrentUser)sub.getSession().getAttribute(BkfmConstants.CURRENT_USER);
	}
	
	/**
	 * 获取用户所属菜单
	 * @return
	 */
	public static List<BkfmMenu> getCurrentUserMenu(){
		CurrentUser current = getCurrentUser();
		return current.getMenuList();
	}
	
	/**
	 * 是否系统管理员
	 * @return
	 */
	public static boolean isAdmin() {
		CurrentUser current = getCurrentUser();
		return current.isSuperAdminUser();
	}
	
	/**
	 * 获取登录用户默认部门
	 * @return
	 */
	public static BkfmUserOrgs getDefaultOrg() {
		CurrentUser current = getCurrentUser();
		if(current.getDefaultDept()==null) {
			throw new ServiceException("用户“"+current.getUser().getUser_name()+"”,没有配置默认所属部门");
		}
		return current.getDefaultDept();
	}
	
	/**
	 * 执行系统登录接口类扩展方法
	 * @param currentUser
	 * @param session
	 */
	public static void executeCustomLoginClass(CurrentUser currentUser,HttpSession session) {
		try {
			String costom_login_class = ConfigUtils.getConfigValue("costom_login_class");
			if(!StringUtils.isEmpty(costom_login_class)) {
				IBkfmCustomLoginService customLoginService = (IBkfmCustomLoginService)Class.forName(costom_login_class).newInstance();
				customLoginService.executeCustomLogin(currentUser, session);
			}
		}catch(Exception e) {
			logger.error("执行登录扩展接口异常",e);
		}
	}
	
	public static void main(String args[]) {
		System.out.println(Md5Utils.hash("1"));
	}
}
